package com.rabbitmq.ChattingRoom.util.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname TokenUtils
 * @Description TODO
 * @Date 2021/07/28 09:38
 * @Created by SHTL
 */
   public class TokenUtils   {
   //设置过期时间
   private static final long EXPIRE_DATE=30 * 24 * 3600 * 1000L; // 一个月
   //token秘钥
   private static final String TOKEN_SECRET = "SHtlLshuaUUHufguGuwu2021BQWE";

   private static final String USERID = "userid";
   private static final String USERNAME = "usernme";
   private static final String PASSWORD = "password";

   /**
    * 通过jwt生成token
    *
    * @param id
    * @param username
    * @param password
    * @return
    */
   public static String token (Long id,String username,String password){

      String token = "";
      try {
         //过期时间
         Date date = new Date(System.currentTimeMillis()+EXPIRE_DATE);
         //秘钥及加密算法
         Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
         //设置头部信息
         Map<String,Object> header = new HashMap<>();
         header.put("typ","JWT");
         header.put("alg","HS256");
         //携带username，password信息，生成签名
         token = JWT.create()
                 .withHeader(header)
                 .withClaim(USERID,+id)
                 .withClaim(USERNAME,username)
                 .withClaim(PASSWORD,password).withExpiresAt(date)
                 .sign(algorithm);
      }catch (Exception e){
         e.printStackTrace();
         return  null;
      }
      return token;
   }

   /**
    * 根据token获取 id
    * @param token
    * @return
    */
   public static Long getId(String token) {
      DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build().verify(token);
      return Long.valueOf(decodedJWT.getClaim(USERID).asLong());
   }

   /**
    * 根据token获取username
    * @param token
    * @return
    */
   public static String getUserName(String token) {
      DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build().verify(token);
      return String.valueOf(decodedJWT.getClaim(USERNAME).asString());
   }


}
